package org.xiaohanghu.starter;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author XiaohangHu
 * */
public abstract class PathUtils {

	public static final String FILE_URL_PREFIX = "file:";

	/**
	 * 屏蔽系统差异，获得"/"分割的路径。
	 * */
	public static String getReallPath(File file) {
		return getReallPath(file.getAbsolutePath());
	}

	/**
	 * 屏蔽系统差异，获得"/"分割的路径。
	 * */
	public static String getReallPath(String path) {
		path = StringUtils.trimToNull(path);
		if (null == path) {
			return null;
		}
		return path.replace(File.separator, "/");
	}

	public static boolean isJarUrl(URL url) {
		return isJarPath(url.getPath());
	}

	public static boolean isJarPath(String path) {
		path = path.toLowerCase();
		if (path.endsWith(".jar") || path.endsWith(".zip")) {
			return true;
		}
		return false;
	}

	public static String getStartJarDir() throws URISyntaxException,
			IOException {
		Class<?> clazz = Main.class;
		URL url = clazz.getResource("");
		String path = url.getPath();
		path = URLDecoder.decode(path, "UTF-8");
		if (path.startsWith(FILE_URL_PREFIX)) {
			path = path.substring(FILE_URL_PREFIX.length());
		}
		int index = path.indexOf("!");
		if (index > 0) {
			path = path.substring(0, index);
		}
		index = path.lastIndexOf("/");
		if (index > 0) {
			path = path.substring(0, index + 1);
		}
		return path;
	}

	public static URI getStartJarUri() throws URISyntaxException, IOException {
		String dirPath = getStartJarDir();
		File file = new File(dirPath);
		return file.toURI();
	}

}
